package com.alibaba.dingtalk.openapi.helper;

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.exception.OApiResultException;
import com.alibaba.dingtalk.openapi.utils.HttpHelper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author kaka
 */
public class DepartmentHelper {

	private static final Logger LOG = LoggerFactory.getLogger(DepartmentHelper.class);

	public static long createDepartment(String accessToken, String name,
                                        String parentId, String order, boolean createDeptGroup ) throws OApiException {
		String url = Env.OAPI_HOST + "/department/create?" +
				"access_token=" + accessToken;
		JSONObject args = new JSONObject();
		args.put("name", name);
		args.put("parentid", parentId);
		args.put("order", order);
		args.put("createDeptGroup", createDeptGroup);
		JSONObject response = HttpHelper.httpPost(url, args);
		if (response.containsKey("id")) {
			return response.getLong("id");
		}
		else {
			throw new OApiResultException("id");
		}
	}


	public static JSONArray listDepartments(String accessToken)
			throws OApiException {
		String url = Env.OAPI_HOST + "/department/list?" +
				"access_token=" + accessToken;

		JSONArray arr = new JSONArray();
		JSONObject response;

		try {
			response = HttpHelper.httpGet(url);
		} catch (OApiException e) {
			LOG.error("访问/department/list 出错" + url, e);
			LOG.error("上面的错误已catch, 打出是为了方便调试！");
			return arr;
		}

		if (response.containsKey("department")) {
			arr = response.getJSONArray("department");
		} else {
			LOG.error("访问/department/list时，返回数据异常" + url);
		}
		return arr;
	}

	/**
	 * 某一个父部门下的子部门列表
	 * @param accessToken 钉钉accessToken
	 * @param depId 部门id
	 * @return 子部门列表
	 * @throws OApiException
	 * kaka
	 * 2016年12月27日 下午6:54:11
	 */
	public static JSONArray listDepartments(String accessToken, Long depId)
			throws OApiException {
		String url = Env.OAPI_HOST + "/department/list?" +
				"access_token=" + accessToken + "&id=" + depId;
		JSONObject response = HttpHelper.httpGet(url);
		if (response.containsKey("department")) {
			JSONArray arr = response.getJSONArray("department");
			return arr;
		}
		else {
			throw new OApiResultException("department");
		}
	}


	public static JSONObject getDepartment(String accessToken, String depId) throws OApiException {
		return getDepartment(accessToken, depId, 0);
	}

	/**
	 * 获取部门实体
	 * @param accessToken
	 * @param depId
	 * @return
	 * @throws OApiException
	 */
	public static JSONObject getDepartment(String accessToken, String depId, int retryTryTimes) throws OApiException {
		String url = Env.OAPI_HOST + "/department/get?access_token=" + accessToken
				+ "&id=" + depId;
		JSONObject responseJson;
		try {
			responseJson = HttpHelper.httpGet(url);
		} catch (OApiException oe) {
			// 您的服务器调用钉钉开放平台当前接口的所有请求都被暂时禁用了（90002）, 90019单公司每秒请求次数超过40次
			// 每个ISV的套件调用单个企业的单个接口频率不可超过1000次/分，否则返回错误码90014 等待60s
			if (oe.getErrCode() == 90002 || oe.getErrCode() == 90019 || oe.getErrCode() == 90014) {
				// 90019/90002 等待1秒钟
				long waitTimeMills = 1000;
				if (oe.getErrCode() == 90014) {
					waitTimeMills = 60000;
				}
				// 重试次数超过3次
				if (retryTryTimes >= 3) {
					LOG.error("getUserDetails 重试超过3次 " + url, oe);
					throw oe;
				} else {
					// 90019等待一秒钟再重试,90014等待一分钟再重试
					try {
						Thread.sleep(waitTimeMills);
					} catch (InterruptedException e) {
						// 恢复中断状态
						Thread.currentThread().interrupt();
						throw oe;
					}
					return getDepartment(accessToken, depId, retryTryTimes + 1);
				}
			} else {
				if (oe.getErrCode() == 50004 || oe.getErrCode() == 60011) {
					// error code: 50004, error message: 请求的部门id不在授权范围内
					//error code: 60011 error message: 没有调用该接口的权限，接口权限申请参考：https://open.dingtalk.com/document/orgapp-server/add-api-permission, {requiredScopess=[qyapi_get_department_list]}
					LOG.warn("访问/department/get 出错： dd-{}, 错误已catch, 打出是为了方便调试！{}", oe.getErrCode(), url + oe.getErrMsg());
					responseJson = new JSONObject();
					responseJson.put("errcode", oe.getErrCode());
					responseJson.put("errmsg", oe.getErrMsg());
				} else {
					LOG.error("访问/department/get 出错, 错误已catch, 打出是为了方便调试！" + url, oe);
					responseJson = new JSONObject();
					responseJson.put("errcode", oe.getErrCode());
					responseJson.put("errmsg", oe.getErrMsg());
				}

			}
		}
		return responseJson;
	}


	public static void deleteDepartment(String accessToken, Long id) throws OApiException{
		String url = Env.OAPI_HOST  + "/department/delete?" +
				"access_token=" + accessToken + "&id=" + id;
		HttpHelper.httpGet(url);
	}


	public static void updateDepartment(String accessToken, String name,
                                        String parentId, String order, long id,
                                        boolean autoAddUser, String deptManagerUseridList, boolean deptHiding, String deptPerimits) throws OApiException{
		String url = Env.OAPI_HOST  + "/department/update?" +
				"access_token=" + accessToken;
		JSONObject args = new JSONObject();
		args.put("name", name);
		args.put("parentid", parentId);
		args.put("order", order);
		args.put("id",id);
		args.put("autoAddUser",autoAddUser);
		args.put("deptManagerUseridList",deptManagerUseridList);
		args.put("deptHiding",deptHiding);
		args.put("deptPerimits",deptPerimits);

		HttpHelper.httpPost(url, args);
	}
}
